# -*- coding: utf-8 -*-
"""Bug分析器 - 分析代码变更和测试用例，找出潜在bug"""

from typing import Dict, List
from .config import config_manager
from .ai_engine import AIEngineFactory


class BugAnalyzer:
    """Bug分析器，基于代码变更和测试用例分析潜在问题"""
    
    def __init__(self, ai_provider="doubao", model=None, key_id=None):
        """
        初始化Bug分析器
        
        Args:
            ai_provider: AI提供商
            model: 模型名称
            key_id: 密钥ID
        """
        self.ai_provider = ai_provider
        self.model = model
        self.key_id = key_id
        self.ai_engine = None
    
    def _init_ai_engine(self):
        """初始化AI引擎"""
        if self.ai_engine is None:
            self.ai_engine = AIEngineFactory.create_engine(
                provider=self.ai_provider,
                model=self.model,
                key_id=self.key_id
            )
    
    def analyze(self, code_changes: str, test_cases: str) -> Dict:
        """
        分析代码变更和测试用例，找出潜在bug
        
        Args:
            code_changes: 代码变更内容（Markdown格式）
            test_cases: 测试用例内容
        
        Returns:
            分析结果字典
        """
        try:
            # 初始化AI引擎
            self._init_ai_engine()

            # 获取提示词模板
            prompt_template = config_manager.get_prompt_from_file("code_analysis_prompt_file")
            print("正在构建AI代码分析prompt...")
            # 格式化提示词
            prompt = prompt_template.format(
                code_changes=code_changes,
                test_cases=test_cases
            )
            
            # 调用AI分析
            print("正在分析代码变更和测试用例...")
            result = self.ai_engine.generate_code_analyse(prompt, "Bug分析")
            
            if not result.get("success"):
                return {
                    "success": False,
                    "error": result.get("error", "分析失败")
                }
            
            analysis_result = result.get("raw_response", "")
            
            # 直接返回原始分析结果（markdown格式）
            return {
                "success": True,
                "raw_analysis": analysis_result
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": f"分析失败: {str(e)}"
            }
    
    def _parse_analysis_result(self, analysis_text: str) -> Dict:
        """
        解析AI分析结果，提取结构化信息
        
        Args:
            analysis_text: AI返回的分析文本
        
        Returns:
            结构化的分析结果
        """
        parsed = {
            "affected_features": [],
            "coverage_issues": [],
            "potential_bugs": [],
            "missing_scenarios": [],
            "recommendations": []
        }
        
        # 简单的文本解析逻辑
        lines = analysis_text.split('\n')
        current_section = None
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            # 识别章节标题
            if "功能点" in line or "涉及的功能" in line:
                current_section = "affected_features"
            elif "覆盖" in line or "测试用例" in line:
                current_section = "coverage_issues"
            elif "bug" in line.lower() or "风险" in line:
                current_section = "potential_bugs"
            elif "遗漏" in line or "缺失" in line:
                current_section = "missing_scenarios"
            elif "建议" in line or "改进" in line:
                current_section = "recommendations"
            
            # 提取列表项
            if line.startswith('-') or line.startswith('*') or line.startswith('•'):
                content = line[1:].strip()
                if current_section and content:
                    # 提取风险等级
                    risk_level = self._extract_risk_level(content)
                    if risk_level:
                        parsed[current_section].append({
                            "content": content,
                            "risk_level": risk_level
                        })
                    else:
                        parsed[current_section].append(content)
            elif line[0].isdigit() and (line[1] == '.' or line[1] == '、'):
                content = line[2:].strip()
                if current_section and content:
                    risk_level = self._extract_risk_level(content)
                    if risk_level:
                        parsed[current_section].append({
                            "content": content,
                            "risk_level": risk_level
                        })
                    else:
                        parsed[current_section].append(content)
        
        return parsed
    
    def _extract_risk_level(self, text: str) -> str:
        """
        从文本中提取风险等级
        
        Args:
            text: 文本内容
        
        Returns:
            风险等级（高/中/低）或None
        """
        text_lower = text.lower()
        if "高风险" in text or "严重" in text or "critical" in text_lower or "high" in text_lower:
            return "高"
        elif "中风险" in text or "medium" in text_lower:
            return "中"
        elif "低风险" in text or "low" in text_lower:
            return "低"
        return None
    
    def format_analysis_report(self, analysis_result: Dict) -> str:
        """
        格式化分析报告为Markdown
        
        Args:
            analysis_result: 分析结果字典
        
        Returns:
            Markdown格式的报告（直接返回原始内容）
        """
        if not analysis_result.get("success"):
            return f"# Bug分析失败\n\n错误: {analysis_result.get('error', '未知错误')}"
        
        # 直接返回原始的markdown格式内容
        return analysis_result.get("raw_analysis", "")


